package com.haiqiu.common.utils.web;

import com.wf.captcha.ArithmeticCaptcha;
import com.haiqiu.common.result.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.RedisConnectionFailureException;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author : haiqiu
 * @date ：2020/12/30 16:22
 * @description: 验证码自定义工具类
 */
@Configuration
public class CaptchaUtil {

    @Autowired
    private RedisUtil redisUtil;

    public Map<String, String> generateCode() {
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(130, 48);
        captcha.setLen(2);
        String key = UUID.randomUUID().toString();
        System.out.println("验证码：" + captcha.text() + "\nkey：" + key);
        Map<String, String> map = new HashMap<>();
        map.put("key", key);
        map.put("image", captcha.toBase64());
        // 存入redis并设置过期时间为2分钟
        if (!redisUtil.set(Constants.CAPTCHA_KEY + key, captcha.text(), 2 * 60L)) {
            throw new RedisConnectionFailureException("redis服务器缓存失败，可能是redis没有启动或者缓存出错");
        }
        return map;
    }
}
